package panels;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import src.Ramo;
import src.CopiarArchivo;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author JMix
 */
public class JPanelRamo extends javax.swing.JPanel {

    public File fFile;
    private VistaDatosRamo padre;
    boolean bandera = true;
        boolean flag1 = false;
        boolean flag2 = false;
    
    /**
     * Creates new form JPanelRamo
     */
    public JPanelRamo() {
        this.fFile = new File("");
        initComponents();
        this.textNombre.requestFocus();
//        this.cantidadNiveles = cantidadNiveles;
//        for (int i=0; i<cantidadNiveles; i++){
//            this.boxNivel.addItem(i+1);
//        }
        this.resetearValidacion();
    }
    
    public void setPadre(VistaDatosRamo padre){
        this.padre = padre;
    }
    
    public void cargarNiveles(int cantidadNiveles){
        boxNiveles.removeAllItems();
        for (int i=0; i<cantidadNiveles; i++)
            this.boxNiveles.addItem(""+(i+1));
    }
    
    public Ramo getRamo(){
       if (validarDatos()){
            String nombre = textNombre.getText();
            int nivel = Integer.parseInt((String)boxNiveles.getSelectedItem());
            int creditos = (this.textCreditos.getText().equals("")) ? 0 : Integer.parseInt(textCreditos.getText());
            int hrsPresenciales = (this.textHrsPresenciales.getText().equals("")) ? 0: Integer.parseInt(textHrsPresenciales.getText());
            int hrsNoPresenciales = (this.textHrsNoPresenciales.getText().equals("")) ? 0 : Integer.parseInt(textHrsNoPresenciales.getText());
            String tipo = (String) boxTipo.getSelectedItem();
            String periodo = (String) boxPeriodo.getSelectedItem();
            String rutaFicha = textRutaFicha.getText();
            Ramo ramo = new Ramo(nombre, nivel, periodo, creditos, hrsPresenciales, hrsNoPresenciales, tipo, rutaFicha);
            return ramo;
        }
        return null;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        textNombre = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        boxNiveles = new javax.swing.JComboBox();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        textCreditos = new javax.swing.JTextField();
        textHrsPresenciales = new javax.swing.JTextField();
        textHrsNoPresenciales = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        boxTipo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        textRutaFicha = new javax.swing.JTextField();
        btnSeleccionar = new javax.swing.JButton();
        btnVer = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        boxPeriodo = new javax.swing.JComboBox();

        jMenuItem1.setText("menu1");
        jMenuItem1.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
        jPopupMenu1.add(jMenuItem1);

        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        textNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNombreActionPerformed(evt);
            }
        });
        textNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textNombreKeyPressed(evt);
            }
        });

        jLabel11.setText("Año:");

        boxNiveles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mostrar(evt);
            }
        });

        jLabel12.setText("(*)Créditos:");

        jLabel13.setText("Hrs presenciales:");

        jLabel14.setText("Hrs no presenciales:");

        textCreditos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textCreditosKeyPressed(evt);
            }
        });

        jLabel15.setText("(*)Nombre:");

        jLabel16.setText("Tipo:");

        boxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "FF", "FD" }));

        jLabel1.setText("Ficha:");

        btnSeleccionar.setText("Seleccionar");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        btnVer.setText("ver");
        btnVer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerActionPerformed(evt);
            }
        });

        jLabel2.setText("Periodo:");

        boxPeriodo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Trimestre 1", "Trimestre 2", "Trimestre 3", "Semestre 1", "Semestre 2", "Anual" }));
        boxPeriodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mostrar(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel13)
                            .addComponent(jLabel14)
                            .addComponent(jLabel16)
                            .addComponent(jLabel12)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textCreditos, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(boxTipo, 0, 88, Short.MAX_VALUE)
                                .addComponent(textHrsPresenciales, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(textHrsNoPresenciales, javax.swing.GroupLayout.Alignment.TRAILING))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textRutaFicha, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18)
                                        .addComponent(boxPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnVer, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnSeleccionar)))))
                        .addGap(0, 122, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel11)
                            .addComponent(jLabel15))
                        .addGap(60, 60, 60)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(boxNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(textNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(boxNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(boxPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel12)
                            .addComponent(textCreditos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel13))
                    .addComponent(textHrsPresenciales, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textHrsNoPresenciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textRutaFicha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnVer)
                    .addComponent(btnSeleccionar))
                .addGap(106, 106, 106))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(new File("."));//situarnos en el directorio actual
        //fc.addChoosableFileFilter(new fGuardarImagen() );//Introducimos el filtro que queremos aplicar
        fc.addChoosableFileFilter(null);
        //fc.setSelectedFile (fFile);//Asignamos el nombre dle archivo por defecto a guardar
        int returnVal = fc.showSaveDialog(this);//Abrimos el selector de diálogo 
        //String ruta = fFile.getPath();
        this.fFile = fc.getSelectedFile();
        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            if( fFile.exists() )
            {
                this.textRutaFicha.setText(fFile.getAbsolutePath());
            }
        }
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerActionPerformed
        String abspath = this.textRutaFicha.getText();
        File file = new File(abspath);
        if (abspath.isEmpty()){
            JOptionPane.showMessageDialog(this, "No hay archivo seleccionado", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (! file.exists()){
            JOptionPane.showMessageDialog(this, "El archivo no existe", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else {
            try {
                    String sSistemaOperativo = System.getProperty("os.name");
                    if (sSistemaOperativo.startsWith("Linux"))
                        Desktop.getDesktop().open(file);
                    else
                        Runtime.getRuntime().exec ("rundll32 SHELL32.DLL,ShellExec_RunDLL "+file);
                
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Ha ocurrido un error", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnVerActionPerformed

    private void textNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textNombreKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.padre.btnAceptar();
    }//GEN-LAST:event_textNombreKeyPressed

    private void mostrar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mostrar
        this.padre.cargarRamosAnteriores(this.boxNiveles.getSelectedIndex()+1, (String)this.boxPeriodo.getSelectedItem());
        //this.padre.limpiarRequisitosSeleccionados();
    }//GEN-LAST:event_mostrar

    private void textCreditosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textCreditosKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.padre.btnAceptar();
    }//GEN-LAST:event_textCreditosKeyPressed

    private void textNombreActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_textNombreActionPerformed
    {//GEN-HEADEREND:event_textNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textNombreActionPerformed

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained

    }//GEN-LAST:event_formFocusGained

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxNiveles;
    private javax.swing.JComboBox boxPeriodo;
    private javax.swing.JComboBox boxTipo;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JButton btnVer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JTextField textCreditos;
    private javax.swing.JTextField textHrsNoPresenciales;
    private javax.swing.JTextField textHrsPresenciales;
    private javax.swing.JTextField textNombre;
    private javax.swing.JTextField textRutaFicha;
    // End of variables declaration//GEN-END:variables

    public void resetearValidacion(){
        this.jLabel15.setForeground(Color.black);
        this.jLabel12.setForeground(Color.black);
        
    }
    
     /**
     * Método que verifica la factibilidad de los campos iniciales para un nuevo curso.
     * @return Retorna un booleano. True si los campos están validos, false si no lo están.
     */
    private boolean validarDatos() {
        //Volvemos los componentes de aviso en su modo predeterminado.
        this.resetearValidacion();
        
        // en caso que no se haya llenado el formulario, no se valida
        if (this.formularioSinLlenar())
            return false;
        
        //Creamos la bandera para saber si los campos son validos.
        boolean bandera = true;
        boolean flag1 = false;
        boolean flag2 = false;
        //Verificamos si el nombre del curso es valido, de lo contrario mostramos un mensaje de aviso.
        if (this.textNombre.getText().equals("")){
           this.jLabel15.setForeground(Color.red);//Volvemos color rojo el jLabel de nombre curso.
           bandera = false;
           flag1 = true;
        }
        
        //Obtenemos el largo de los créditos.
        int aux = textCreditos.getText().length();
        //Verificamos si se ingresó algun valor, de lo contrario mostraremos un mensaje de aviso.
        if (aux == 0){
            this.jLabel12.setForeground(Color.red);//Volvemos color rojo el jLabel del creditaje.
            bandera = false;
            flag1 = true;
        }
        
        else{
            //Verificamos si lo ingresado en créditos es un entero.
            for (int i=0; i<aux; i++){
                if(!(textCreditos.getText().charAt(i) >= '0' && textCreditos.getText().charAt(i) <= '9')){
                    this.jLabel12.setForeground(Color.red);//Volvemos color rojo el jLabel del creditaje.
                    bandera = false;
                    flag2 = true;
                    break;
                }
            }
            if(!flag2){
                if(Integer.parseInt(this.textCreditos.getText()) < 1){
                    this.jLabel12.setForeground(Color.red);//Volvemos color rojo el jLabel del creditaje.
                    bandera = false;
                    flag2 = true;
                }
            }
        }
        
        if( flag1 && flag2){
             JOptionPane.showMessageDialog(padre, "Los campos con (*) son obligatorios."+ "\n" +"Cantidad de creditos debe ser un valor entero mayor a cero.", padre.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        else if(flag1){
            JOptionPane.showMessageDialog(padre, "Los campos con (*) son obligatorios.", padre.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        else if(flag2){
            JOptionPane.showMessageDialog(padre,"Cantidad de creditos debe ser un valor entero mayor a cero.", padre.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        //Si hay algun dato invalido retornamos un false.
        if(!bandera){
            return false;
        } 
        return true;
    }
    
    public void reset(int cantidadSemestres) {
       this.textNombre.setText("");
       this.textCreditos.setText("");
       this.textHrsPresenciales.setText("");
       this.textHrsNoPresenciales.setText("");
       this.textRutaFicha.setText("");
       this.boxNiveles.setSelectedIndex(0);
       this.boxPeriodo.setSelectedIndex(3);
       this.boxTipo.setSelectedIndex(0);
       this.cargarNiveles(cantidadSemestres);
       this.textNombre.requestFocus();
    }
    
    public void mostrarInfoRamo(Ramo ramo){
        this.textNombre.setText(ramo.getNombre());
        this.textCreditos.setText("" + ramo.getCreditos());
        this.textHrsPresenciales.setText("" + ramo.getHrsPresenciales());
        this.textHrsNoPresenciales.setText("" + ramo.getHrsNoPresenciales());
        this.textRutaFicha.setText(ramo.getRutaFicha());
        this.boxNiveles.setSelectedIndex(ramo.getNivel()-1);
        this.boxPeriodo.setSelectedItem(ramo.getPeriodo());
    }

    public JTextField getTextCreditos() {
        return textCreditos;
    }

    public void setTextCreditos(JTextField textCreditos) {
        this.textCreditos = textCreditos;
    }

    public JTextField getTextHrsNoPresenciales() {
        return textHrsNoPresenciales;
    }

    public void setTextHrsNoPresenciales(JTextField textHrsNoPresenciales) {
        this.textHrsNoPresenciales = textHrsNoPresenciales;
    }

    public JTextField getTextHrsPresenciales() {
        return textHrsPresenciales;
    }

    public void setTextHrsPresenciales(JTextField textHrsPresenciales) {
        this.textHrsPresenciales = textHrsPresenciales;
    }

    public boolean formularioSinLlenar() {
        if (this.textNombre.getText().equals("") &&
            this.textCreditos.getText().equals("") &&
            this.textHrsPresenciales.getText().equals("") &&
            this.textHrsNoPresenciales.getText().equals(""))
            return true;
        return false;
    }  

    public JLabel getjLabel12() {
        return jLabel12;
    }

    public JLabel getjLabel15() {
        return jLabel15;
    }
    
}
